package com.github.pig.admin.util;

import com.github.pig.common.constant.CommonConstant;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.util.Date;

/**
 * 上传文件工具类
 */
public class FileUpload {

    public static void fileUp(String file) throws Exception{
        String url = CommonConstant.FILE_ADDRESS_UP;
        CloseableHttpClient client = HttpClients.createDefault();

        BASE64Decoder decoder = new BASE64Decoder();
        byte[] decoderBytes = decoder.decodeBuffer(file);

        HttpPost httppost = new HttpPost(url);
        long fileName = new Date().getTime();
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("uploadfile", new File(file));
        HttpEntity reqEntity = builder.build();
        httppost.setEntity(reqEntity);
        CloseableHttpResponse resp = client.execute(httppost);
        String str = EntityUtils.toString(resp.getEntity());
        System.out.println(str);
        resp.close();
        client.close();
    }
}
